package com.software.project_view.entity;
import com.software.project_view.utils.StringUtil;
import org.apache.commons.codec.binary.Hex;
import lombok.Data;

import java.util.Date;

@Data
public class Block {

    private static final String  ZERO_HASH = Hex.encodeHexString(new byte[32]);
    private String hash;
    private String previousHash;
    private String data;
    private long timestamp;
    private int nonce;

    public Block(String data,String previousHash) {
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = new Date().getTime();
        this.hash = calculateHash();
    }

    public String calculateHash() {
        String calculateHash = StringUtil.applySha256(previousHash + Long.toString(timestamp) + Integer.toString(nonce) +data);
        return calculateHash;
    }

    public void mineBlock(int difficulty) {
        String target = StringUtil.getDifficultyString(difficulty);
        while (!hash.substring(0,difficulty).equals(target)) {
            nonce ++;
            hash = calculateHash();
        }
        System.out.println("挖到了。。。" + hash);
    }
}
